<?php


namespace app\api\controller\xiluhouse;


use app\common\controller\Api;
use app\common\model\xiluhouse\RentalCollection;
use app\common\model\xiluhouse\RentalOrderHouse;
use app\common\model\xiluhouse\RentalTag;
use app\common\model\xiluhouse\UserProfile;
use app\common\model\xiluhouse\Village;
use app\common\model\xiluhouse\VillageApply;
use app\common\model\xiluhouse\VillageBroker;
use app\common\validate\xiluhouse\market\MarketHouse;
use app\common\validate\xiluhouse\RentalOrder;
use app\common\validate\xiluhouse\UserAuth;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Validate;
use function fast\array_except;
use function fast\array_get;

/**
 * 经纪人模块
 * @package app\api\controller\xiluhouse
 */

class Broker extends Api
{
    protected $noNeedRight = ['*'];

    protected $noBroker = ['apply'];

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub

        $user_profile = UserProfile::where('user_id',$this->auth->id)->find();
        if(!$this->auth->match($this->noBroker) && $user_profile->is_broker < 1){
            $this->error("非经纪人/房东不可访问");
        }
    }

    /**
     * 房东/经纪人申请
     */
    public function apply(){
        $params = $this->request->param('');
        if(!is_array($params)){
            $this->error("非法参数");
        }
        $params['user_id'] = $this->auth->id;
        $params['is_broker'] = array_get($params,'is_broker',2);
        $validate = new UserAuth();
        if(!$validate->check($params)){
            $this->error($validate->getError());
        }
        $exist = \app\common\model\xiluhouse\UserAuth::where('user_id',$this->auth->id)
            ->where('is_broker',2)
            ->whereIn('check_status',[0,1])
            ->find();

        if($exist && $exist->check_status != 2){
            $this->error("您已有申请记录");
        }
        $params['check_status'] = 0;
        $params['refuse_reason'] = '';
        if($exist){
            $exist->allowField(true)->save($params);
        }else{
            $exist = \app\common\model\xiluhouse\UserAuth::create($params);
        }
        $this->success('申请成功，请等待审核',$exist);
    }


    /**
     * 我的房源管理
     */
    public function rental_lists(){
        $params = $this->request->param('');
        $status = array_get($params,'status');
        $where['user_id'] = $this->auth->id;
        if(in_array($status,['normal','hidden'])){
            $where['rental.status'] = $status;
        }
        if($q = $this->request->param('q')){
            $where['rental.name|village.name'] = ['like',"%$q%"];
        }
        //日期条件
        if($date = $this->request->param('date')){
            $time1 = date('Y-m-01 00:00:00', strtotime($date));
            $time2 = date('Y-m-d 23:59:59', strtotime("$time1 +1 month -1 day"));
            $where['rental.createtime'] = ['between',[strtotime($time1),strtotime($time2)]];
        }
        $lists = \app\common\model\xiluhouse\Rental::field("id,name,village_id,user_id,price,image,space,house_tag_ids,status,createtime,updatetime")->with(['village'=>function($query){
            $query->withField('id,name,prov,city,region,street');
        }])
            ->where($where)
            ->order('rental.updatetime','desc')
            ->paginate()
            ->each(function ($row){
                //$row->append(['house_tag_ids_text_arr']);
                $row->house_tag_ids_text_arr = $row->rentalTags();
                $row->updatetime_text = date('m.d H:i',$row->updatetime);
                $row->createtime_date = date('m.d H:i',$row->createtime);
            });
        $this->success('查询成功',$lists);
    }

    /**
     * 上下架
     */
    public function multi_status(){
        $params = $this->request->param('');
        $rental_id = array_get($params,'rental_id');
        $status = array_get($params,'status');
        if(!$rental_id || !$status || !in_array($status,['normal','hidden'])){
            $this->error('参数错误');
        }
        $where['user_id'] = $this->auth->id;
        $row = \app\common\model\xiluhouse\Rental::where('id',$rental_id)->where($where)->find();
        if(!$row){
            $this->error('无权操作');
        }
        if(($status == 'hidden' && in_array($row->status,['normal'])) || ($status == 'normal' && in_array($row->status,['hidden']))){
            $row->status = $status;
            $row->allowField(true)->save();
        }else{
            $this->error('状态不可操作');
        }
        $this->success($status=='normal'?"上架成功":'下架成功',$row);
    }


    /**
     * 代理房源管理
     */
    public function agent_rental_lists(){
        //$params = $this->request->param('');
//        $village_ids = VillageBroker::where('broker_user_id',$this->auth->id)->column('village_id')?:[];
//        if(!$village_ids){
//            $this->error('还未有代理小区呦~');
//        }
//        $where['village2.id'] = ['in',$village_ids];
        $where['rental.status'] = 'normal';
        $where['rental.is_public'] = '1';
        $where['rental.user_id'] = ['neq',$this->auth->id];
        if($q = $this->request->param('q')){
            $where['rental.name|village2.name'] = ['like',"%$q%"];
        }
        $lists = \app\common\model\xiluhouse\Rental::alias("rental")
            ->join('xiluhouse_village_broker village_broker','village_broker.village_id=rental.village_id')
            ->field("id,name,village_id,user_id,price,image,space,house_tag_ids,status,updatetime")
            ->with(['village2'=>function($query){
            $query->withField('id,name,prov,city,region,street');
        }])
            ->where('village_broker.broker_user_id',$this->auth->id)
            ->where($where)
            ->order('rental.updatetime','desc')
            ->paginate()
            ->each(function ($row){
                //$row->append(['house_tag_ids_text_arr']);
                $row->house_tag_ids_text_arr = $row->rentalTags();
                $row->updatetime_text = date('m.d H:i',$row->updatetime);
            });
        $this->success('查询成功',$lists);
    }
    /**
     * 发起签约前获取房东信息
     */
    public function rental_lessor(){
        $params = $this->request->param('');
        if(!$rental_id = array_get($params,'rental_id')){
            $this->error('参数错误');
        }

        $rental = \app\common\model\xiluhouse\Rental::where('id',$rental_id)->find();
        if(!$rental){
            $this->error('租房信息错误');
        }
        $user_auth = \app\common\model\xiluhouse\UserAuth::get(['user_id'=>$rental->user_id]);
        $this->success('获取成功',$user_auth ?? []);
    }

    /**
     * 发起签约
     * 谁发布的房源，谁就是房东
     */
    public function rental_sign(){
        $params = $this->request->param('');
        $validate = new RentalOrder();
        if(!$validate->check($params)){
            $this->error($validate->getError());
        }
        $params['user_id'] = $this->auth->id;
//        if($params['lessor_mobile'] && $lessor_user = \app\common\model\xiluhouse\User::field('id,nickname,mobile')->where('mobile',$params['lessor_mobile'])->find()){
//            $this->error('房东手机号未注册');
//        }

        if($params['renter_mobile'] &&  !$rental_user = \app\common\model\xiluhouse\User::field('id,nickname,mobile')->where('mobile',$params['renter_mobile'])->find()){
            $this->error('租客手机号未注册');
        }
        $params['renter_user_id'] = isset($rental_user) ? $rental_user['id'] : 0;
        $params['renter_pay_money'] = bcadd(bcadd($params['deposit'], $params['renter_money'],2),$params['renter_medium_money'],2);
        $params['lessor_pay_money'] = $params['lessor_medium_money'];

        $rental = \app\common\model\xiluhouse\Rental::field("id,name,village_id,user_id,price,image,images,room_num,ting_num,wei_num,space,face,floor_num,content,building_descript,cosult_tel,house_type_id,house_tag_ids,status,updatetime")->with(['village2'=>function($query){
            $query->withField('id,name,prov,city,region,street,addr,lat,lng');
        }])
            ->where('rental.id',$params['rental_id'])
            ->order('rental.updatetime','desc')
            ->find();
        if(!$rental || $rental->status == 'hidden'){
            $this->error('当前房源不存在已下架');
        }
        //$rental->append(['house_tag_ids_text_arr']);
        $params['order_type'] = $rental->user_id == $this->auth->id ? 'direct' : 'agent';
        $params['platform'] = 'wxmini';
        $params['order_no'] = "S".date('YmdHis').mt_rand(100,99999);
        $params['rent_start_date'] = strtotime($params['rent_start_date']);
        $params['rent_end_date'] = strtotime($params['rent_end_date']);
        $params['order_state'] = 1;
        $params['state'] = 1;
        $params['pay_status'] = 0;
        $params['lessor_state'] = 0;
        $params['lessor_user_id'] = $rental->user_id;
        $rental_order = new \app\common\model\xiluhouse\RentalOrder();
        $tags = $rental->rentalTags();
        $rentalTags = [];
        foreach ($tags as $tag){
            if(isset($tag['tag']['name'])){
                $rentalTags[] = $tag['tag']['name'];
            }
        }
        unset($tag);
        $building_descript = $rental->rentalTags(2);
        $descript = [];
        foreach ($building_descript as $v){
            if(isset($v['type_tag']['name']) && isset($v['tag']['name'])){
                $descript[] = [$v['type_tag']['name']=>$v['tag']['name']];
            }
        }
        Db::startTrans();
        try {
            $rental_order->allowField(true)->save($params);
            #房子基本资料
            RentalOrderHouse::create([
                'order_id'      =>  $rental_order->id,
                'rental_id'     =>  $rental->id,
                'name'          =>  $rental->name,
                'village_id'    =>  $rental->village_id,
                'user_id'       =>  $rental->user_id,
                'price'         =>  $rental->price,
                'image'         =>  $rental->image,
                'images'        =>  $rental->images,
                'village_name'  =>  $rental->village2->name,
                'prov'          =>  $rental->village2->prov,
                'city'          =>  $rental->village2->city,
                'region'        =>  $rental->village2->region,
                'street'        =>  $rental->village2->street,
                'addr'          =>  $rental->village2->addr,
                'lat'           =>  $rental->village2->lat,
                'lng'           =>  $rental->village2->lng,
                'room_num'      =>  $rental->room_num,
                'ting_num'      =>  $rental->ting_num,
                'wei_num'       =>  $rental->wei_num,
                'space'         =>  $rental->space,
                'face'          =>  $rental->face,
                'floor_num'     =>  $rental->floor_num,
                'house_type_text'=> $rental->housetype ? $rental->housetype->name : '',
                'house_tag_text'=>  $rentalTags?implode(',',$rentalTags):'',
                'content'       =>  $rental->content,
                'building_descript'=>  $descript ? json_encode(',',$descript) : '',
                'cosult_tel'    =>  $rental->cosult_tel,
            ]);

        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('发起签约成功',$rental_order);
    }

    /**
     * 发起的签约列表
     */
    public function sign_lists(){
        $state = $this->request->param('state',-1);

        $query = \app\common\model\xiluhouse\RentalOrder::with(['rental','rentalUser'=>function($query){
            $query->withField(['id','nickname','avatar']);
        },'lessorUser'=>function($query){
            $query->withField(['id','nickname','avatar']);
        }])
            ->where('rental_order.user_id|rental_order.lessor_user_id',$this->auth->id);

        if($q = $this->request->param('q')){
            $query->where('rental_order.lessor_name|rental_order.lessor_mobile|rental_order.renter_name|rental_order.renter_mobile|rental.name','like',"%{$q}%");
        }

        switch ($state){
            case -1:
                #已取消
                $query->where('order_state',2);
                break;
            case 1:
                #待签约-两方都未签约
                $query->where('order_state',1)
                    ->where('state',1)
                    ->where('lessor_state',0);
                break;
            case 2:
                #签约中-有一方未签约
                $query->where('order_state',1)
                    ->where(function ($query){$query->where('state = 2 AND lessor_state = 0')->whereOr('state=1 AND lessor_state=1');});
                break;
            case 3:
                #待支付-租客和房东都签约,但是租客未支付
                $query->where('order_state',1)
                    ->where("state",2)
                    ->where('lessor_state',1)
                    ->where('pay_status',0);
                break;
            case 4:
                #已完成-已签约-租客已支付
                $query->where('order_state',3)
                    ->where('state',2)
                    ->where('lessor_state',1)
                    ->where('pay_status',1);
                break;
        }
        $user_id = $this->auth->id;
        $lists = $query->order('updatetime','desc')
            ->paginate()
            ->each(function ($row) use($user_id){
                $row->rental->append(['house_tag_text_arr']);
                $row->is_lessor = $user_id == $row->lessor_user_id ? 1 : 0;
            });

        $this->success('查询成功',$lists);
    }

    /**
     * 经纪人/房东取消签约
     */
    public function cancel_sign(){
        $rental_order_id = $this->request->param('rental_order_id');
        if(!$rental_order_id){
            $this->error('参数错误');
        }
        $rental_order = \app\common\model\xiluhouse\RentalOrder::where('id',$rental_order_id)->find();
        if(!$rental_order){
            $this->error('当前订单不存在');
        }
        if(!in_array($rental_order->checkinfo,[0,1,2,3])){
            $this->error('当前状态不可取消');
        }
        if($rental_order->user_id != $this->auth->id && $this->auth->id != $rental_order->lessor_user_id) {
            $this->error('没有权限');
        }
        $rental_order->order_state = '2';

        if($this->auth->id == $rental_order->lessor_user_id){
            //房东取消
            $rental_order->lessor_state = -1;
        }

        $rental_order->canceltime = time();
        $rental_order->save();
        $this->success('签约取消成功');
    }

    /**
     * 代理小区
     */
    public function my_village(){
        $lists = VillageBroker::with(['village'=>function($query){
            $query->where('status','normal')->withField(['id','name','prov','city','region','street','addr']);
        }])
            ->where('broker_user_id',$this->auth->id)
            ->order('id','desc')
            ->paginate();
        $this->success('查询成功',$lists);
    }

    /**
     * 小区申请
     */
    public function apply_village(){
        $params = $this->request->param('');
        if(!$village_id = array_get($params,'village_id')){
            $this->error('小区参数错误');
        }
//        $village = Village::get($village_id);
//        if(!$village || $village->status == 'hidden'){
//            $this->error('小区不存在或已下架');
//        }
        $exist = VillageBroker::where('broker_user_id',$this->auth->id)
            ->whereIn('village_id',$village_id)
            ->find();
        if($exist){
            $this->error('您已拥有该小区');
        }
//        $village_apply = VillageApply::where('broker_user_id',$this->auth->id)
//            ->where('village_id',$village_id)
//            ->where('check_status','0')
//            ->find();
//        if($village_apply){
//            $this->error('您申请的小区正在审核中');
//        }
        $row = VillageApply::create([
            'broker_user_id'    =>  $this->auth->id,
            'village_id'        =>  $village_id
        ]);
        $this->success('申请成功',$row);
    }

    /**
     * 添加小区
     */
    public function add_village(){
        $params = $this->request->param('');
        $params['user_id'] = $this->auth->id;
        $validate = new Validate([
            'name|小区名称'            => 'require',
            'user_id|发布用户'         => 'require',
            'prov|省份'               => 'require',
            'city|市区'               => 'require',
            'region|区/县'            => 'require',
            'street|街道'             => 'require',
            'addr|详细地址'            => 'require',
            'images|小区图片'          => 'require'
        ]);
        if(!$validate->check($params)){
            $this->error($validate->getError());
        }
        $model = new \app\common\model\xiluhouse\Village();
        if($model->where('name',$params['name'])->where('prov',$params['prov'])->where('city',$params['city'])->find()){
            $this->error('当前小区已存在');
        }
        $params['image'] = !empty($params['image']) ? $params['image'] :explode(',',$params['images'])[0];

        $address = $params['prov'] . $params['city'] . $params['region'] . $params['street'] . $params['addr'];
        $result = getGeo($address);
        if ($result['status'] == 0) {
            $this->error('获取经纬度失败，请选择正确的地址');
        }
        $params['lat'] = $result['lat'];
        $params['lng'] = $result['lng'];
        $params['check_status'] = 0;

        Db::startTrans();
        try {
            $ret = $model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('添加成功',$ret);
    }

    /**
     * 移除小区
     */
    public function remove_village(){
        $village_broker_id = $this->request->post('village_broker_id');
        if(!$village_broker_id) {
            $this->error('参数错误');
        }
        $row = VillageBroker::where('id',$village_broker_id)
            ->where('broker_user_id',$this->auth->id)
            ->order('id','desc')
            ->find();
        if(!$row){
            $this->error('小区已不存在');
        }
        $row->delete();
        $this->success('移除成功');
    }

    /**
     * 添加房源
     */
    public function add_rental(){
        $params = $this->request->only(["id","image","village_id","name","house_no","house_type_id","rental_mode_id","images","is_public","in_time","seetime","price","space","face","floor_num","ting_num","room_num","wei_num","content",'tag','status']);
        $params['user_id'] = $this->auth->id;
        $validate = new Validate([
            'name|租房名称'            => 'require',
            'village_id|所属小区'      => 'require|gt:0',
            'user_id|发布用户'         => 'require',
            'price|价格'              => 'gt:0',
            'images|图片'             => 'require',
            'space|面积'              => 'require',
            'face|朝向'               => 'require',
            //'buildingtime|建造时间'    => 'require',
            //'fixturestime|装修时间'    => 'require',
            'house_type_id|房源类型'   => 'require',
            'rental_mode_id|租赁模式'  => 'require',
            'content|详情描述'         => 'require',
            //'building_descript|建筑信息'=> 'require',
        ]);
        if(!$validate->check($params)){
            $this->error($validate->getError());
        }
        $village = Village::get($params['village_id']);
        if(!$village || $village->check_status !== 1){
            $this->error("小区还在审核中");
        }
        if(!$village || $village->status == 'hidden'){
            $this->error("小区已下架");
        }
        $params['image'] = !empty($params['image']) ? $params['image'] :explode(',',$params['images'])[0];
        //$params['building_descript'] = json_encode($params['building_descript']);
        $house_tag_ids = [];
        $house_tag_type_ids = [];
        foreach ($params['tag'] as $tag){
            $house_tag_ids[] = $tag['tag_id'];
            if(isset($house_tag_type_ids[$tag['tag_type_id']])){
                $house_tag_type_ids[$tag['tag_type_id']] .= ','.$tag['tag_id'];
            }else{
                $house_tag_type_ids[$tag['tag_type_id']]=$tag['tag_id'];
            }
        }
        unset($tag);
        //halt($house_tag_type_ids);
        $params['house_tag_ids'] = implode(',',$house_tag_ids);
        $model = new \app\common\model\xiluhouse\Rental();
        Db::startTrans();
        try {
            if($rental_id = array_get($params,'id')){
                unset($params['id']);
                $row = $model->get($rental_id);
               // halt($params);
                $ret = $row->allowField(true)->save($params);
                $result2 = RentalTag::setTagIds($row,$house_tag_type_ids,'edit');
            }else{
                $ret = $model->allowField(true)->save($params);
                $result2 = RentalTag::setTagIds($model,$house_tag_type_ids);
                $row = $model;
            }
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('保存成功',$row);
    }

    /**
     * @title   房源详情
     * @desc    房源详情
     * @param int $id   0   房源id
     */
    public function rental_detail()
    {
        $rental_id = $this->request->param('rental_id/d', 0);
        if (!$rental_id) {
            $this->error('参数错误');
        }
        $info = \app\common\model\xiluhouse\Rental::with(['village2'=>function($query){
            $query->withField(['id','name','prov','city','region','street','addr']);
        }])
            ->field('rental.id,image,images,village_id,rental.name,house_type_id,is_public,fixturestime,buildingtime,price,space,face,floor_num,ting_num,room_num,wei_num,content')
            ->where('rental.id',$rental_id)
            ->find();
        if (!$info) {
            $this->error('查询不到该房源');
        }
        $info->append(['images_arr']);
        $this->success('', $info);
    }


    /**
     * 角标
     */
    public function state_bubble(){

        #已取消
        $cancel_count = \app\common\model\xiluhouse\RentalOrder::with(['rental'])
            ->where('rental_order.user_id|rental_order.lessor_user_id',$this->auth->id)->where('order_state',2)->count('rental_order.id');
        #待签约-两方都未签约
        $unsign_count = \app\common\model\xiluhouse\RentalOrder::with(['rental'])
            ->where('rental_order.user_id|rental_order.lessor_user_id',$this->auth->id)
            ->where('order_state',1)
            ->where('state',1)
            ->where('lessor_state',0)
            ->count('rental_order.id');
        #签约中-有一方未签约
        $signing_count = \app\common\model\xiluhouse\RentalOrder::with(['rental'])
            ->where('rental_order.user_id|rental_order.lessor_user_id',$this->auth->id)
            ->where('order_state',1)
            ->where(function ($query){$query->where('state = 2 AND lessor_state = 0')->whereOr('state=1 AND lessor_state=1');})->count('rental_order.id');
        #待支付-租客和房东都签约,但是租客未支付
        $unpaid_count = \app\common\model\xiluhouse\RentalOrder::with(['rental'])
            ->where('rental_order.user_id|rental_order.lessor_user_id',$this->auth->id)
            ->where('order_state',1)
            ->where("state",2)
            ->where('lessor_state',1)
            ->where('pay_status',0)
            ->count('rental_order.id');
        #已完成-已签约-租客已支付
        $sign_finish_count = \app\common\model\xiluhouse\RentalOrder::with(['rental'])
            ->where('rental_order.user_id|rental_order.lessor_user_id',$this->auth->id)
            ->where('order_state',3)
            ->where('state',2)
            ->where('lessor_state',1)
            ->where('pay_status',1)
            ->count('rental_order.id');
        $this->success('查询成功',[
            'cancel_count'=>$cancel_count,
            'unsign_count'=>$unsign_count,
            'signing_count'=>$signing_count,
            'unpaid_count'=>$unpaid_count,
            'sign_finish_count'=>$sign_finish_count,
        ]);
    }


    /**********************二手房***********************/

    /**
     * 代理房源管理
     */
    public function agent_market_lists(){
        $params = $this->request->param('');
        $where['market_house.status'] = 'normal';
        $where['market_house.state'] = '2';
        $where['market_house.is_public'] = '1';
        $where['market_house.user_id'] = ['neq',$this->auth->id];
        if($q = array_get($params,'q')){
            $where['village2.name'] = ['like',"%$q%"];
        }
        $lists = \app\common\model\xiluhouse\market\MarketHouse::alias("market_house")
            ->join('xiluhouse_village_broker village_broker','village_broker.village_id=market_house.village_id')
            ->fieldRaw("id,market_house.village_id,total_price,price,image,space,room_num,ting_num,wei_num,market_house.updatetime")
            ->with(['village2'=>function($query){
                $query->withField('id,name,prov,city,region,street');
            }])
            ->where('village_broker.broker_user_id',$this->auth->id)
            ->where($where)
            ->order('market_house.updatetime','desc')
            ->paginate()
            ->each(function ($row){
                $row->append(['image_text']);
                $row->updatetime_text = date('m.d H:i',$row->updatetime);
            });
        $this->success('查询成功',$lists);
    }

    /**
     * 我的二手房源
     */
    public function market_house(){
        $params = $this->request->param('');
        $status = array_get($params,'status');
        $where['user_id'] = $this->auth->id;
        if(in_array($status,['normal','hidden'])){
            $where['market_house.status'] = $status;
        }
        if($q = $this->request->param('q')){
            $where['village.name'] = ['like',"%$q%"];
        }
        $lists = \app\common\model\xiluhouse\market\MarketHouse::field("id,village_id,user_id,total_price,price,image,space,status,createtime,updatetime")->with(['village'=>function($query){
            $query->withField('id,name,prov,city,region,street');
        }])
            ->where($where)
            ->order('market_house.updatetime','desc')
            ->paginate()
            ->each(function ($row){
                $row->append(['image_text']);
                $row->updatetime_text = date('m.d H:i',$row->updatetime);
                $row->createtime_date = date('m.d H:i',$row->createtime);
            });
        $this->success('查询成功',$lists);
    }


    /**
     * 上下架
     */
    public function market_multi_status(){
        $params = $this->request->param('');
        $marketId = array_get($params,'market_id');
        $status = array_get($params,'status');
        if(!$marketId || !$status || !in_array($status,['normal','hidden'])){
            $this->error('参数错误');
        }
        $where['user_id'] = $this->auth->id;
        $row = \app\common\model\xiluhouse\market\MarketHouse::where('id',$marketId)->where($where)->find();
        if(!$row){
            $this->error('无权操作');
        }
        if(($status == 'hidden' && in_array($row->status,['normal'])) || ($status == 'normal' && in_array($row->status,['hidden']))){
            $row->status = $status;
            $row->allowField(true)->save();
        }else{
            $this->error('状态不可操作');
        }
        $this->success($status=='normal'?"上架成功":'下架成功',$row);
    }

    public function add_market(){
        $params = $this->request->only(['id','village_id','house_no','image','images','room_images','video_file','house_no','total_price','price','space','face','total_floor','floor_num','period','room_num','ting_num','wei_num','is_elevator','purpose_id','decoration_id','is_unique','buy_years','parking_lot','property_right','view_status','content','is_public'],'post');
        $params['user_id'] = $this->auth->id;
        $validate = new MarketHouse();
        if(!$validate->check($params)){
            $this->error($validate->getError());
        }
        $village = Village::get($params['village_id']);
        if(!$village || $village->check_status !== 1){
            $this->error("小区还在审核中");
        }
        if(!$village || $village->status == 'hidden'){
            $this->error("小区已下架");
        }
        $model = new \app\common\model\xiluhouse\market\MarketHouse();
        Db::startTrans();
        try {
            if($market_id = array_get($params,'id')){
                $row = $model->where('id',$market_id)->find();
                $ret = $row->allowField(true)->save(array_except($params,['id']));
            }else{
                $ret = $model->allowField(true)->save($params);
                $row = $model;
            }
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('保存成功',$row);
    }

    /**
     * @title   房源详情
     * @desc    房源详情
     * @param int $id   0   房源id
     */
    public function market_detail()
    {
        $market_id = $this->request->param('market_id/d', 0);
        if (!$market_id) {
            $this->error('参数错误');
        }
        $info = \app\common\model\xiluhouse\market\MarketHouse::with(['village'=>function($query){
            $query->withField(['id','name','prov','city','region','street','addr']);
        }])
            ->field('market_house.*')
            ->where('market_house.id',$market_id)
            ->find();
        if (!$info) {
            $this->error('查询不到该房源');
        }
        $info->append(['images_arr','room_images_text']);
        $this->success('', $info);
    }

}